package com.xzc.one.common.aop;

import com.xzc.one.common.ce.MyClass;
import com.xzc.one.common.config.redis.RedisUtil;
import com.xzc.one.model.User;
import org.springframework.stereotype.Component;

import javax.servlet.FilterConfig;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * TokenFilter
 *
 * @author xiongzhicong
 * @create 2019-11-02 12:27
 **/
@Component
@WebFilter(urlPatterns = "/**", filterName = "tokenFilter")
public class TokenFilter implements Filter {

    private static final String[] passPaths = {"user", "common", "druid", "demo"};//不拦截的uri

    @Override
    public void init(FilterConfig filterConfig) {
        System.out.println("TokenFilter.init");
    }

    private boolean isPass(String uri) {
        for (String passPath : passPaths) {
            if (uri.startsWith("/" + passPath)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        System.out.println(((HttpServletRequest) servletRequest).getSession().getId());
        String requestURI = ((HttpServletRequest) servletRequest).getRequestURI();
        if (isPass(requestURI))
            filterChain.doFilter(servletRequest, servletResponse);
        else {
            String token = ((HttpServletRequest) servletRequest).getHeader(MyClass.Token);
            if (token == null) return;
            token = MyClass.Token + ":" + token;
            if (RedisUtil.exists(User.class, token)) {
                User currentUser = (User) RedisUtil.get(User.class, token);
                RedisUtil.set(currentUser, token, RedisUtil.Time_day);
                ((HttpServletRequest) servletRequest).getSession().setAttribute(MyClass.Token, currentUser);
                filterChain.doFilter(servletRequest, servletResponse);
            }
        }
    }

    @Override
    public void destroy() {
        System.out.println("TokenFilter.destroy");
    }
}
